import { requestConfig } from '@/services/config';
import { isArray } from '@/utils/checkType';
import { deepClone } from '@/utils/format';
import type { ProFormUploadButtonProps } from '@ant-design/pro-components';
import { ProFormUploadButton } from '@ant-design/pro-components';
import type { UploadFile } from 'antd';
import { message } from 'antd';
import { useEffect, useMemo, useState } from 'react';
export type File = {
  uid: string;
  name: string;
  url: string;
};
export interface IProFormUploadProps extends ProFormUploadButtonProps {
  file: File | File[];
  onChangeFile: (file: File[]) => void;
}

export default function ProFormUpload(props: IProFormUploadProps) {
  const { file = [], onChangeFile, ...resetProps } = props;

  const fileList = useMemo(() => (isArray(file) ? file : [file]), [file]);
  const [uploadFileList, setUploadFileList] = useState<UploadFile[]>(fileList);

  useEffect(() => {
    if (fileList.length !== uploadFileList.length) {
      setUploadFileList(fileList);
    }
  }, [fileList]);

  const getFile = (uploadFile: UploadFile) => {
    const { uid, name } = uploadFile;
    const { uploadedFiles = [] } = uploadFile.response;
    const url = uploadedFiles && uploadedFiles.length ? uploadedFiles[0] : '';
    const file: File = { uid, name, url: `${requestConfig.imageURL}${url}` };
    return file;
  };
  const findFile = (uploadFile: UploadFile, fileList: File[]) => {
    const { uid, name, url } = getFile(uploadFile);
    for (let [index, file] of fileList.entries()) {
      if (file.uid === uid && file.name === name && file.url === url) {
        return index;
      }
    }
    return -1;
  };
  const add = (uploadFile: UploadFile) => {
    const newFileList: File[] = deepClone(fileList);
    const file = getFile(uploadFile);
    newFileList.push(file);
    onChangeFile(newFileList);
  };
  const remove = (uploadFile: UploadFile) => {
    const newFileList: File[] = deepClone(fileList);
    const index = findFile(uploadFile, newFileList);
    if (index > -1) newFileList.splice(index, 1);

    onChangeFile(newFileList);
  };

  return (
    <ProFormUploadButton
      {...resetProps}
      action={requestConfig.uploadURL}
      fieldProps={{
        name: 'files',
        multiple: true,
        listType: 'picture-card',
        headers: { Authorization: `Bearer ${window.localStorage.getItem('access_token')}` },
        fileList: uploadFileList,
        onChange: (info) => {
          const { file, fileList } = info;
          const isLt50M = (info.file.size || 0) / 1024 / 1024 < 50;
          if (isLt50M) {
            setUploadFileList([...fileList]);
          } else {
            setUploadFileList([]);
          }

          if (file.status === 'removed') {
            remove(info.file);
          } else if (file.status === 'done') {
            if (file?.response) {
              if (file?.response?.failed) {
                file!.status = 'error';
                return message.warning(file?.response?.message);
              } else if (file?.response?.status === 500) {
                file!.status = 'error';
                return message.warning('上传失败');
              }
              add(info.file);
            }
          }
        },
      }}
    />
  );
}
